package application;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.event.ActionEvent;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.Pagination;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.TilePane;
import javafx.util.Callback;
import java.awt.Desktop;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import util.CentralControl;
import util.News;

public class MainController implements Initializable {

	@FXML
	private TextField text;

	@FXML
	private AnchorPane pane1;

	@FXML
	private Button btn;

	// 分割，第二页面
	@FXML
	private CheckBox rb12;

	@FXML
	private CheckBox rb22;

	@FXML
	private CheckBox rb32;

	@FXML
	private CheckBox rb42;

	@FXML
	private Pagination pagination;

	@FXML
	private Label notFoundWarning;

	@FXML
	private ComboBox<String> cob;

	@FXML
	private TextField text2;

	@FXML
	private AnchorPane pane2;

	@FXML
	private Label keyword;

	@FXML
	private Button btn2;

	@FXML
	private TilePane loadingAnimation;

	@FXML
	private FlowPane amCarrier;

	@FXML
	private Label crewingTip;

	@FXML
	private ToggleButton up;

	@FXML
	private ToggleButton down;

	@FXML
	private ToggleButton flesh;

	String inputContent = null;

	public static ArrayList<News> newsList;

	CentralControl s; // 已在Main类中创建

	int timeOrder = -1;

	/**
	 * 输入内容为空时，弹出警告框
	 */
	public void showDialog() {
		Alert alert = new Alert(AlertType.WARNING);
		alert.setTitle("温馨提示");
		alert.setHeaderText("文本框内容为空");
		alert.setContentText("请输入内容");
		alert.showAndWait();
	}

	@FXML
	void enterPress(KeyEvent event) {
		if (event.getCode() == KeyCode.ENTER) {
			if (text.getText().trim().equals("")) {
				showDialog();
			} else {
				toSecondStage();
			}
		}
	}

	@FXML
	void press(ActionEvent event) {
		if (text.getText().trim().equals("")) {
			showDialog();
		} else {
			toSecondStage();
		}
	}

	public void toSecondStage() {
		this.inputContent = text.getText();
		text2.setText(inputContent);
		boolean[] jd = { false, false, false, false };
		ArrayList<News> news = new ArrayList<>();
		news = s.get("title", inputContent, -1, -1, jd);
		if (news.size() == 0) {
			s.startCrew();
			setAnimation();
		} else
			this.setPagination(news);
		setCobAndOrder();
		pane1.setVisible(false);
		pane2.setVisible(true);
	}

	/**
	 * 初始化直接显示光标
	 */
	public void setcursor() {
		text.requestFocus();
	}

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		// pane1.setVisible(true);
		pane2.setVisible(false);
		btn.setId("btn");
		btn2.setId("btn");
	}

	///////////// 分界线，第二页面的代码

	/**
	 * @param event 回车输入
	 */
	@FXML
	void enterPress2(KeyEvent event) {
		if (event.getCode() == KeyCode.ENTER) {
			handleAction();
		}
	}

	/**
	 * @param event 点击“搜索”按钮
	 */
	@FXML
	void press2(ActionEvent event) {
		handleAction();
	}

	/**
	 * 把处理的部分单独挑出
	 */
	public void handleAction() {
		setCobAndOrder();
		if (text2.getText().trim().equals("")) {
			showDialog();
		} else {
			boolean[] jd = getTickBox2();
			ArrayList<News> news = new ArrayList<>();
			this.inputContent = text2.getText();
			news = s.get("title", inputContent, timeOrder, -1, jd);
			if (news.size() == 0) {
				s.startCrew();
				setAnimation();
			} else
				setPagination(news);
		}
	}

	/**
	 * 设置时间那个条&把对应升降序的阴影化
	 */
	public void setCobAndOrder() {
		cob.setValue("时间");
		cob.getItems().setAll("一天内", "一周内", "一月内");
		if (timeOrder == 1) {
			up.setSelected(true);
		} else if (timeOrder == 0) {
			down.setSelected(true);
		}
	}

	/**
	 * @return 获取打勾的平台，原第二个平台
	 */
	public boolean[] getTickBox2() {
		CheckBox[] rbs = { rb12, rb22, rb32, rb42 };
		boolean[] jd = { false, false, false, false }; // 用于监控改变
		for (int i = 0; i < rbs.length; i++) {
			CheckBox cb = rbs[i];
			if (cb.isSelected()) {// 判断选择哪个按钮，在调入具体的数据库
				jd[i] = true;
			}
		}
		return jd;
	}

	/**
	 * scrollpane中放入tilepane,tilepane中放入10个hbox,每个hbox放入borderpane,borderpane不同部位放标题、原文、图片
	 */
	public void setPagination(ArrayList<News> news) {
		flesh.setSelected(false);
		loadingAnimation.setVisible(false);
		notFoundWarning.setVisible(false);
		pagination.setVisible(true);
		if (news.size() <= 200) {
			pagination.setPageCount(news.size() / 10 + 1);
		} else
			pagination.setPageCount(20);
		pagination.setPageFactory(new Callback<Integer, Node>() { // 设置分页
			public Node call(Integer pageIndex) {
				ScrollPane scrollpane = new ScrollPane();
				scrollpane.setId("scrollpane");
				scrollpane.setMaxSize(885, 649);
				TilePane tilepane = new TilePane(Orientation.VERTICAL);
				tilepane.setPrefRows(10);
				tilepane.setVgap(10);
				tilepane.setTileAlignment(Pos.TOP_LEFT);
				for (int i = 0; i < 10; i++) { // 每一页展示10条新闻
					int tmp = i;
					if (news.size() > pageIndex * 10 + i) {
						HBox box = new HBox();
						box.setPrefWidth(865);
						box.setPrefHeight(200);
						box.setId("box");
						FlowPane flowpane = new FlowPane();
						flowpane.setId("flowpane");
						ArrayList<String> segment = new ArrayList<>();
						if (news.get(pageIndex * 10 + i).getTitle() == null
								|| news.get(pageIndex * 10 + i).getTitle().isEmpty()
								|| news.get(pageIndex * 10 + i).getTitle().equals(""))
							continue; // 如果标题内容为空，则跳过
						if (news.get(pageIndex * 10 + i).getTitle().length() < 33)
							segment = SplitTitle.splitTitle(inputContent, news.get(pageIndex * 10 + i).getTitle()); // 标题分为包含于inputContent的连续字段和无关连续字段
						else
							segment = SplitTitle.splitTitle(inputContent, news.get(pageIndex * 10 + i).getTitle().substring(0, 33));
						for (int j = 0; j < segment.size(); j++) {
							Hyperlink hl = new Hyperlink(segment.get(j));
							if (inputContent.contains(segment.get(j)) == true) hl.setId("keyword");
							flowpane.getChildren().add(hl);
						}
						if (news.get(pageIndex * 10 + i).getTitle().length() >= 33) { // 设置标题Hyperlink长度，还需考虑非全汉字的情况
							flowpane.getChildren().add(new Hyperlink("..."));
							flowpane.setPrefWidth(770);
						} else
							flowpane.setPrefWidth(news.get(pageIndex * 10 + i).getTitle().length() * 23);
						Hyperlink title = new Hyperlink("", flowpane);
						title.setMinHeight(25);
						title.setPrefHeight(25);
						title.setMaxHeight(25);
						title.setOnAction((ActionEvent showWeb) -> {
							try {
								int count; // 点击超链接后改变字体颜色
								count = flowpane.getChildren().size();
								Hyperlink[] hls = new Hyperlink[count];
								for (int j = 0; j < count; j++) {
									if (flowpane.getChildren().get(j) instanceof Hyperlink) {
										hls[j] = (Hyperlink) flowpane.getChildren().get(j);
										hls[j].setVisited(true);
									}
								}

								Desktop desktop = Desktop.getDesktop(); // 实现点击超链接弹出网页
								if (Desktop.isDesktopSupported() && desktop.isSupported(Desktop.Action.BROWSE)) {
									URI uri = new URI(news.get(pageIndex * 10 + tmp).getUrl());
									desktop.browse(uri);
								}
							} catch (Exception exp) {
								System.out.println(exp);
							}
						});
						Label content = new Label(news.get(pageIndex * 10 + i).getContent());
						content.setId("content");
						content.setMinHeight(130);
						content.setPrefHeight(130);
						content.setMaxHeight(130);
						BorderPane borderpane = new BorderPane();
						borderpane.setPrefWidth(865);
						borderpane.setTop(title);
						borderpane.setCenter(content);
						if (news.get(pageIndex * 10 + i).getImgUrl().isEmpty()
								|| news.get(pageIndex * 10 + i).getImgUrl() == null) {
						} else {
							Image image = new Image(news.get(pageIndex * 10 + i).getImgUrl(), 130, 100, false, false,
									true);
							ImageView iv = new ImageView(image);
							borderpane.setLeft(iv);
							iv.setId("imageview");
						}
						borderpane.setBottom(new FlowPane(new Label("出版方：" + news.get(pageIndex * 10 + i).getPublisher()
								+ "          发布时间：" + Time.getDate(news.get(pageIndex * 10 + i).getSummitTime()))));
						box.getChildren().add(borderpane);
						tilepane.getChildren().add(box);
					}
				}
				scrollpane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
				scrollpane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
				scrollpane.setContent(tilepane);
				return scrollpane;
			}
		});
	}

	@FXML
	void menuButtonClickAction(ActionEvent event) {
		setByTime();
	}

	/**
	 * @param event 点击“升序”的处理
	 */
	@FXML
	void setUpSequence(ActionEvent event) {
		down.setSelected(false); // 把倒序设成未选定，避免误解
		if (timeOrder == 1) { // 已经点击过升序了，再点，就是取消
			timeOrder = -1;
		} else {
			this.timeOrder = 1;
		}
		setByTime();
	}

	/**
	 * @param event 点击“降序”的处理
	 */
	@FXML
	void setDownSequence(ActionEvent event) {
		up.setSelected(false); // 把升序设成未选定，避免误解
		if (timeOrder == 0) { // 已经点击过降序了，再点，就是取消
			timeOrder = -1;
		} else {
			this.timeOrder = 0;
		}
		setByTime();
	}

	/**
	 * 根据时间去设置news
	 */
	public void setByTime() {
		boolean[] jd = getTickBox2();
		ArrayList<News> news = new ArrayList<>();
		if (cob.getValue() == "一天内") {
			news = s.get("title", inputContent, timeOrder, 0, jd);
		} else if (cob.getValue() == "一周内") {
			news = s.get("title", inputContent, timeOrder, 1, jd);
		} else if (cob.getValue() == "一月内") {
			news = s.get("title", inputContent, timeOrder, 2, jd);
		} else {
			news = s.get("title", inputContent, timeOrder, -1, jd);
		}
		if (news.size() == 0) {
			System.out.println("not found!");
			setNotFoundInfo();
		} else
			setPagination(news);
	}
	
	/**
	 * 显示动画
	 * @param event 按下爬取开关
	 */
	@FXML
	public void setFlesh(ActionEvent event) {
//		if (checkNet()) {
//			if(this.flesh.isSelected()) {
//				this.flesh.setText("关闭");
//				s.startCrew();
//				loadingAnimation.setPrefTileHeight(50);
//				loadingAnimation.setVisible(true);
//				notFoundWarning.setVisible(false);
//				pagination.setVisible(false);
//				Animation a = new Animation(loadingAnimation,amCarrier);
//				Animation.ispress=true;
//				a.handRunAm();
//			}
//			else {
//				this.flesh.setText("开启");
//				s.stopCrew();
//				loadingAnimation.setVisible(false);
//				Animation.ispress=false;
//				boolean[] jd = getTickBox2();
//				ArrayList<News> news = new ArrayList<>();
//				news = s.get("title", inputContent, timeOrder, -1, jd);
//				if (news.size() == 0) setNotFoundInfo();
//				else setPagination(news);
//			}
//		} else
//			showConnectFail();
		CheckNet cn = new CheckNet(loadingAnimation, amCarrier,flesh);
		cn.setMainCtrl(this);
		Thread cnd = new Thread(cn);
		if(!this.flesh.isSelected()) {   //关闭爬取
			this.flesh.setText("开启");
			s.stopCrew();
			loadingAnimation.setVisible(false);
			Animation.ispress=false;
			boolean[] jd = getTickBox2();
			ArrayList<News> news = new ArrayList<>();
			news = s.get("title", inputContent, timeOrder, -1, jd);
			if (news.size() == 0) setNotFoundInfo();
			else setPagination(news);
		}
		else {
			cnd.start();
			this.flesh.setText("关闭");
			loadingAnimation.setPrefTileHeight(50);
			loadingAnimation.setVisible(true);
			notFoundWarning.setVisible(false);
			pagination.setVisible(false);
			Animation a = new Animation(loadingAnimation,amCarrier);
			Animation.ispress=true;
			a.handRunAm();
		}
	}
	/**
	 * 
	 * @return 检查网络状态，正常返回true，很快，如果无网络，要等大概5s
	 */
//	public boolean checkNet() {
//		URL url = null;
//		try {
//			url = new URL("http://baidu.com");
//			try {
//				InputStream in = url.openStream();
//				in.close();
//				return true;
//			} catch (IOException e) {
//				return false;
//			}
//		} catch (MalformedURLException e) {
//			e.printStackTrace();
//		}
//		return false;
//	}

	/**
	 * 无网络警告框
	 */
	public void showConnectFail() {
		Alert alert = new Alert(AlertType.WARNING);
		alert.setTitle("温馨提示");
		alert.setHeaderText("当前网络已断开");
		alert.setContentText("请检查你的网络状态");
		alert.showAndWait();
	}

	/**
	 * 动画加载线程
	 */
	public void setAnimation() {
		loadingAnimation.setPrefTileHeight(50);
		loadingAnimation.setVisible(true);
		notFoundWarning.setVisible(false);
		pagination.setVisible(false);
		pane1.setVisible(false);
		Animation a = new Animation(loadingAnimation, amCarrier);
		a.setMainCtrl(this);
		Thread am = new Thread(a);
		am.start();
	}

	/**
	 * 如果没有新闻时，显示找不到的信息
	 */
	public void setNotFoundInfo() {
		keyword.setText(inputContent);
		loadingAnimation.setVisible(false);
		pagination.setVisible(false);
		notFoundWarning.setVisible(true);
	}

	/**
	 * @param s 设置CentralControl
	 */
	public void setCenCtrl(CentralControl s) {
		this.s = s;
	}
}
